﻿using System;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace FileCopy
{
    public class ExceptionManager
    {
        static ExceptionManager()
        {
            ResetLogFile();
        }
        public static void ResetLogFile()
        {
            string strLogpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ExceptionLog");
            if (!Directory.Exists(strLogpath))
                Directory.CreateDirectory(strLogpath);
            string strLogFile = String.Format("{0:yyyy_MM_dd}_{1}.log", DateTime.Now, Process.GetCurrentProcess().Id);
            strLogFile = Path.Combine(strLogpath, strLogFile);
            FileStream fs = new FileStream(strLogFile, FileMode.OpenOrCreate);
            Trace.Listeners.Add(new TextWriterTraceListener(fs));
            Trace.AutoFlush = true;
        }

        public static void TraceWrite(Exception e)
        {
            Trace.WriteLine(String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));
            StringBuilder sb = new StringBuilder(5000);
            RecurseErrorStack(e, ref sb);
            Trace.WriteLine(sb.ToString());
            Trace.WriteLine("");
            Trace.Unindent();
        }

        public static void TraceWrite(Exception e, string location)
        {
            Trace.WriteLine(String.Format("{0:yyyy-MM-dd HH:mm:ss} {1}", DateTime.Now, location));
            StringBuilder sb = new StringBuilder(5000);
            RecurseErrorStack(e, ref sb);
            Trace.WriteLine(sb.ToString());
            Trace.WriteLine("");
            Trace.Unindent();
        }

        public static void TraceWrite(string ErrorMsg, string location)
        {
            Trace.WriteLine(String.Format("{0:yyyy-MM-dd HH:mm:ss} {1} : {2}", DateTime.Now, location, ErrorMsg));
            Trace.Unindent();
        }

        private static void RecurseErrorStack(Exception e, ref StringBuilder sb)
        {
            sb.Append("ERROR: ");
            sb.AppendLine(e.Message);
            sb.AppendLine(e.StackTrace);
            if (null != e.InnerException)
                RecurseErrorStack(e.InnerException, ref sb);
        }
    }
}
